package com.bblocks.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Slf4j
@Component("redissonConfig")
@ConditionalOnProperty(name = "bblocks.redisson.enabled", matchIfMissing = false)
public class RedissonConfig {

	@Value("${spring.redis.host}")
	private String host;

	@Value("${spring.redis.port:6379}")
	private String port;

	@Value("${spring.redis.password}")
	private String password;

	@Value("${spring.redis.database:0}")
	private Integer database;

	@Value("${yz.redisson.minimumIdleSize:12}")
	private Integer minimumIdleSize;

	@Bean
	public RedissonClient redissonClient(){
		Config config = new Config();
		config.setTransportMode(TransportMode.NIO);

		SingleServerConfig singleServerConfig = config.useSingleServer();
		//可以用"rediss://"来启用SSL连接
		singleServerConfig.setAddress("redis://" + host + ":" + port);
		if(StrUtil.isNotEmpty(password))
			singleServerConfig.setPassword(password);

		singleServerConfig.setDatabase(database);
		//最小空闲连接数
		singleServerConfig.setConnectionMinimumIdleSize(minimumIdleSize);

		RedissonClient redisson = Redisson.create(config);
		log.info("启动RedissonClient！");
		return redisson;
	}
}